<template>
	<view class="AICont" :style="{ height: webStyle.height }">
		<view class="title-box" :style="{ 'padding-top': inf0Pt + 'vh' }">
			<image class="back" @click="back" :src="imgPath + 'AICont/back-arrow.svg'" mode="widthFix"></image>
			<view class="title">AI文案</view>
			<view class="back"></view>
		</view>
		<view class="residue-tips" v-if="0">
			剩余脚本生成
			<text style="color: #f00">8</text>
			次
		</view>
		<view class="main-form">
			<view class="form-item">
				<view class="label">
					<view class="text">选择分类</view>
					<view class="subText"></view>
				</view>
				<picker @change="mainTabbarIndChange" :value="mainTabbarInd" :range="mainTabbar.map((e) => e.name)">
					<view class="box select-box">
						<view class="text" v-if="mainTabbarInd != -1">{{ mainTabbar[mainTabbarInd].name }}</view>
						<view class="text nac" v-else>{{ "请选择分类" }}</view>
						<view class="right">
							<image class="icon" :src="imgPath + 'AICont/arrow.svg'" mode="widthFix"></image>
						</view>
					</view>
				</picker>
			</view>
			<template v-if="mainTabbar[mainTabbarInd] && mainTabbar[mainTabbarInd].val">
				<view class="form-item" v-for="(item, index) in mainTabbar[mainTabbarInd].val" :key="item.menuId">
					<view class="label">
						<view class="text">{{ item.name }}</view>
						<view class="subText"></view>
					</view>
					<view v-if="item.categoryType == 'input'" class="box input-box">
						<input class="text" type="text" placeholder-class="nac" @input="(evnet) => replaceInput(evnet, item, index)" :value="item.val" :placeholder="item.prompt || '请输入' + item.name" />
					</view>
					<view v-if="item.categoryType == 'textarea'" class="box textarea-box">
						<textarea class="text" placeholder-class="nac" @input="(evnet) => replaceInput(evnet, item, index)" :value="item.val" :maxlength="-1" :placeholder="item.prompt || '请输入' + item.name"></textarea>
						<!-- <view class="num">0 / 100</view> -->
					</view>
					<picker v-if="['select', 'radio'].includes(item.categoryType)" @change="(evnet) => bindPickerChange(evnet, item, index)" :value="item.ind" :range="item.catalogList" range-key="name">
						<view class="box select-box">
							<view class="text" v-if="item.ind != -1">{{ item.catalogList[item.ind].name }}</view>
							<view class="text nac" v-else>{{ "请选择分类" }}</view>
							<view class="right">
								<image class="icon" :src="imgPath + 'AICont/arrow.svg'" mode="widthFix"></image>
							</view>
						</view>
					</picker>
				</view>
			</template>
		</view>
		<view class="f">
			<view class="submit" @tap="submit">生成脚本</view>
		</view>
		<LoginDialog ref="LoginDialog" :show="LoginDialogShow" @successFn="loginDialogShowSucc" @changeShow="changeLoginDialogShow" style="z-index: 999"></LoginDialog>
	</view>
</template>

<script>
import { tools } from "../../utils/util";
import * as api from "@/api/createVideo.js";
export default {
	name: "AICont",
	data() {
		return {
			imgPath: tools.imgPath,
			inf0Pt: 0,
			systemInfo: {},
			webStyle: {
				height: ""
			},
			LoginDialogShow: false,
			pageInfo: null,
			mainTabbarInd: 0,
			mainTabbar: []
		};
	},
	methods: {
		// 跳转页面
		toPage(path, type = "navigateTo") {
			uni[type]({
				url: path
			});
		},
		// 监听登录弹出层显示
		changeLoginDialogShow(val) {
			this.LoginDialogShow = val;
		},
		// 登陆成功数据刷新
		loginDialogShowSucc() {
			this.getData();
		},
		// 生成语料
		async submit() {
			let currMainTabbar = this.mainTabbar[this.mainTabbarInd];
			let nextFlag = true;
			let userInput = currMainTabbar.val.reduce((p, e, i) => {
				if (e.isRequired && e.val === "") nextFlag = false;
				p[e.signSn] = `${e.val}${e.signSn3 ? "{{" + e.signSn3 + "}}" : ""}`;
				return p;
			}, {});
			// if (!nextFlag) return tools.easyToast("请补充以上必填内容！");
			uni.showLoading({
				title: "请稍后..."
			});
			let userInputStr = JSON.stringify(userInput);
			let res = await api.postChatCreatScirept({
				title: currMainTabbar.name,
				userInput: userInputStr,
				industry: currMainTabbar.menuId
			});
			if (!res) return tools.easyToast("生成失败，请重试！");
			let temp = JSON.parse(res.data);
			let val = Object.values(temp)
				.map((e) => e.match(/[\n]*[“]*(.*)[”]*[\n]*/)[1])
				.join("")
				.replace(/[”“"']/g, "");
			uni.setStorageSync("aiCont", {
				updateType: "AiCont",
				cont: val
			});
			uni.hideLoading();
			switch (this.pageInfo?.toPage) {
				case "index/2": //AI文案
					let [pageName, footerBarListAc] = this.pageInfo.toPage.split("/");
					uni.setStorageSync("toHome", {
						footerBarListAc: footerBarListAc
					});
					uni.reLaunch({
						url: `/pages/${pageName}/${pageName}`
					});
					break;
				default:
					this.toPage("/pages/createAvatar/createAvatar", "reLaunch");
					break;
			}
		},
		// 监听input事件
		replaceInput(event, item, index) {
			this.mainTabbar[this.mainTabbarInd].val[index].val = event.target.value;
		},
		// picker改变事件
		bindPickerChange(event, item, index) {
			let ind = event.detail.value;
			item = this.mainTabbar[this.mainTabbarInd].val[index];
			item.ind = ind;
			item.val = item.catalogList[ind]?.name ?? "";
			item.signSn3 = item.catalogList[ind]?.signSn ?? "";
		},
		// 切换分类
		mainTabbarIndChange(e) {
			this.mainTabbarInd = e.detail.value;
		},
		// 获取分类
		async getData() {
			let res = null;
			if (this.pageInfo.ids && this.pageInfo.ids.length) {
				res = await api.postChatCreatScireptById(this.pageInfo.ids);
			} else {
				res = await api.getMotifQueryMenu();
			}
			if (!res) return;
			let objData = res.data;
			let mainTabbar = Object.entries(objData).reduce((prev, [key, val], ind) => {
				// 通过正则截取有效信息
				let tempStr = key.match(/MotifHintLevelVo\((.*)\)/);
				if (!tempStr) return prev;

				// 拆分信息，将每条键值对保存为数组，并转为object
				let tempArr = tempStr[1]?.split(",") ?? [];
				let obj = tempArr.reduce((p, e) => {
					let [okey, oval] = e.split("=");
					p[okey.trim()] = oval; //通过后端生成一级数据
					p.val = val.map((ele) => {
						//这里可以修改二级菜单
						// ele.signSn = (() => {
						//     let liao = `ABCDEFGHIJKLMNOPQRSTUVWXYZ`;
						//     let val = '';
						//     for (let index = 0; index < 4; index++) {
						//         val += liao[tools.randomNum(0, liao.length - 1)];
						//     };
						//     return val;
						// })();
						// ele.prompt = '提示语啊提示语';
						// ele.textRestrict = 20;
						// ele.isRequired = true;
						ele.ind = 0;
						ele.val = ele.catalogList[ele.ind]?.name ?? "";
						ele.signSn3 = ele.catalogList[ele.ind]?.signSn ?? "";
						return ele;
					});
					// p.menuId = tools.createID();
					return p;
				}, {});

				// 保存obj
				prev.push(obj);
				return prev;
			}, []);
			this.mainTabbar = mainTabbar.reverse();
		},
		// 回退
		back() {
			let pages = getCurrentPages();
			if (pages.length > 1) {
				uni.navigateBack({
					delta: 1
				});
			} else {
				uni.setStorageSync("toHome", {
					footerBarListAc: 1
				});
				uni.reLaunch({
					url: "/pages/index/index"
				});
			}
		},
		// 获取页面参数
		initPageInfo(opt) {
			let pageInfo = uni.getStorageSync("AIContInfo");
			this.pageInfo = pageInfo;
			uni.removeStorageSync("AIContInfo");
		},
		// 获取系统info
		initSystemInfo(isUpdate = true) {
			const that = this;
			return new Promise((resolve, reject) => {
				uni.getSystemInfo({
					success(payload) {
						if (isUpdate) {
							that.systemInfo = payload;
							that.webStyle.height = `${that.systemInfo.windowHeight}px`;
							console.log("initSystemInfo", that.systemInfo);
							switch (that.systemInfo.uniPlatform) {
								case "web":
									that.inf0Pt = 4.5;
									break;
								case "app":
									that.inf0Pt = 4.5;
									break;
								case "mp-weixin":
									that.inf0Pt = 4.5;
									break;
							}
						}
						resolve(payload);
					}
				});
			});
		}
	},
	onLoad(opt) {
		this.initPageInfo(opt);
		this.getData();
	},
	created() {
		this.initSystemInfo();
	}
};
</script>

<style lang="scss">
.AICont {
	width: 100vw;
	height: 100vh;
	overflow: hidden;
	// background: radial-gradient(#034748 0%, #010c1f 100%);
	background: radial-gradient(#117d62 0%, #010c1f 100%);
	box-sizing: border-box;
	padding: 3vw;
	display: flex;
	flex-direction: column;

	.title-box {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.back {
			width: 6vw;
		}

		.title {
			font-size: 36rpx;
			font-weight: 400;
			color: rgba(255, 255, 255, 1);
		}
	}

	.residue-tips {
		margin: 6vw 3vw;
		font-size: 36rpx;
		font-weight: 400;
		color: rgba(243, 173, 51, 1);
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 2vw 0vw;
		background: linear-gradient(90deg, rgba(247, 225, 111, 0) 0.17%, rgba(252, 219, 96, 0.47) 51.66%, rgba(247, 225, 111, 0) 100%);
	}

	.main-form {
		flex: 1;
		overflow: auto;

		.form-item {
			margin: 6vw 0vw;

			.label {
				font-weight: 400;
				color: rgba(255, 255, 255, 1);
				display: flex;
				align-items: end;

				.text {
					font-size: 36rpx;
					margin-right: 2vw;
				}

				.subText {
					font-size: 24rpx;
				}
			}

			.box {
				margin-top: 2.5vw;
				border-radius: 3vw;
				background: rgba(255, 255, 255, 0.08);
				border: 1px solid rgba(56, 108, 92, 1);
				backdrop-filter: blur(26px);
				min-height: 10vw;
				box-sizing: border-box;
				padding: 1vw 2.5vw;

				.text {
					font-size: 28rpx;
					font-weight: 400;
					color: rgba(255, 255, 255, 1);

					&.nac {
						color: rgba(255, 255, 255, 0.46);
					}
				}

				&.select-box {
					width: 100%;
					display: flex;
					justify-content: space-between;
					align-items: center;

					.right {
						.icon {
							width: 1.68vw;
						}
					}
				}

				&.input-box {
					display: flex;
					align-items: center;
					height: 100%;
					width: 100%;

					.text {
						width: 100%;
					}
				}

				&.textarea-box {
					height: 36vw;
					overflow: auto;
					position: relative;

					.text {
						width: 100%;
						height: 100%;
						overflow: auto;
					}
					.num {
						position: absolute;
						bottom: 1vw;
						right: 1vw;
						font-size: 20rpx;
						font-weight: 400;
						color: rgba(255, 255, 255, 0.46);
					}
				}
			}
		}
	}

	.f {
		height: 52vw;
		box-sizing: border-box;
		padding: 10vw 0vw;

		.submit {
			width: 100%;
			opacity: 1;
			border-radius: 10px;
			background: rgba(0, 153, 127, 1);
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 36rpx;
			font-weight: 500;
			color: rgba(255, 255, 255, 1);
			padding: 2.5vw 0vw;
		}
	}
}
</style>
